package com.jwkj.collector.web;

import com.ghgande.j2mod.modbus.Modbus;
import com.ghgande.j2mod.modbus.io.ModbusTCPTransaction;
import com.ghgande.j2mod.modbus.msg.ReadMultipleRegistersResponse;
import com.ghgande.j2mod.modbus.msg.WriteCoilResponse;
import com.jwkj.collector.master.TcpRTUMaster;
import com.jwkj.collector.server.CollectorServer;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Arrays;
import java.util.concurrent.ConcurrentMap;

@RestController
public class HelloController {
    private static final Logger logger = LoggerFactory.getLogger(ModbusTCPTransaction.class);

    @RequestMapping("/hello")
    public String index() {
        ConcurrentMap<String, TcpRTUMaster> masters = CollectorServer.getSockets();
        if (masters.size() > 0) {
            for (TcpRTUMaster i : masters.values()) {
                ReadMultipleRegistersResponse res = (ReadMultipleRegistersResponse) i.readRequest(0, Modbus
                        .READ_HOLDING_REGISTERS, 0, 15);
                Arrays.stream(res.getRegisters()).forEach(register -> {
                    logger.info("-------------" + register.getValue());
                });
            }
        }
        return "Hello World";
    }

    @RequestMapping("/open")
    public String open() {
        ConcurrentMap<String, TcpRTUMaster> masters = CollectorServer.getSockets();
        if (masters.size() > 0) {
            for (TcpRTUMaster i : masters.values()) {
                WriteCoilResponse res = (WriteCoilResponse) i.writeRequest(0, Modbus.WRITE_COIL, 0, 0);
            }
        }
        return "Hello World";
    }

    @RequestMapping("/open1")
    public String open1() {
        ConcurrentMap<String, TcpRTUMaster> masters = CollectorServer.getSockets();
        if (masters.size() > 0) {
            for (TcpRTUMaster i : masters.values()) {
                WriteCoilResponse res = (WriteCoilResponse) i.writeRequest(0, Modbus.WRITE_COIL, 1, 0);
            }
        }
        return "Hello World";
    }

    @RequestMapping("/close")
    public String close() {
        ConcurrentMap<String, TcpRTUMaster> masters = CollectorServer.getSockets();
        if (masters.size() > 0) {
            for (TcpRTUMaster i : masters.values()) {
                WriteCoilResponse res = (WriteCoilResponse) i.writeRequest(0, Modbus.WRITE_COIL, 0, 1);
            }
        }
        return "Hello World";
    }

    @RequestMapping("/close1")
    public String close1() {
        ConcurrentMap<String, TcpRTUMaster> masters = CollectorServer.getSockets();
        if (masters.size() > 0) {
            for (TcpRTUMaster i : masters.values()) {
                WriteCoilResponse res = (WriteCoilResponse) i.writeRequest(0, Modbus.WRITE_COIL, 1, 1);
            }
        }
        return "Hello World";
    }

}